package com.example.parking.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.List;

public class JwtUtil {
    private static final String DEFAULT_SECRET = "please-change-this-secret-32-bytes-minimum-!!!";
    private static final long EXP_MS = 2 * 60 * 60 * 1000; // 2h

    private static Key buildKey(String secret) {
        if (secret == null || secret.isBlank()) {
            secret = DEFAULT_SECRET;
        }
        // Ensure at least 32 bytes for HS256
        if (secret.length() < 32) {
            secret = String.format("%1$-32s", secret).replace(' ', '0');
        }
        return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
    }

    private static final Key KEY = buildKey(
            System.getenv("JWT_SECRET") != null ? System.getenv("JWT_SECRET") : System.getProperty("jwt.secret")
    );

    public static String generate(String username, List<String> roles) {
        return Jwts.builder()
                .setSubject(username)
                .claim("roles", roles)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXP_MS))
                .signWith(KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    public static Claims parse(String token) {
        return Jwts.parserBuilder().setSigningKey(KEY).build().parseClaimsJws(token).getBody();
    }
}


